package com.may.wlrj.services;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.async.DeferredResult;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.may.wlrj.dao.GatewayDAO;
import com.may.wlrj.dao.LockDAO;
import com.may.wlrj.dao.MissionDAO;
import com.may.wlrj.dao.UserDAO;
import com.may.wlrj.entity.GateWayEntity;
import com.may.wlrj.entity.LockOpenLogEntity;
import com.may.wlrj.entity.LockUserEntity;
import com.may.wlrj.entity.MissionEntity;
import com.may.wlrj.entity.OrganizationEntity;
import com.may.wlrj.entity.UserEntity;
import com.may.wlrj.entity.UserLogEntity;
import com.may.wlrj.finger.ZZFingerUtil;
import com.may.wlrj.mqtt.MqttHeader;
import com.may.wlrj.mqtt.RegisterResp;
import com.may.wlrj.util.MQTTUtil;
import com.may.wlrj.util.XinLongUtil;

@Service
@Transactional
public class GateWayService {
	public static final String MQTT_RES_TOPIC = "reslock";
	private Logger log = Logger.getLogger(GateWayService.class);
	private GatewayDAO gatewayDao;
	
    @Autowired
    public void setGatewayDao(GatewayDAO gatewayDao){
        this.gatewayDao =gatewayDao;
    }
    
    private UserDAO userDao;
    @Autowired
    public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}
    
    private LockDAO lockDao;    
    @Autowired
	public void setLockDao(LockDAO lockDao) {
		this.lockDao = lockDao;
	}
    
    private MissionDAO missionDao;    
    @Autowired
	public void setMissionDao(MissionDAO missionDao) {
		this.missionDao = missionDao;
	}

	public String getgatewaylist(String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	ArrayNode rootnode = mapper.createArrayNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;	
    	int pageNumber = 0;
    	int pageSize = 0;
    	String orgname = "";
    	String mac = "";
    	try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			orgname =rootNode.get("orgname").asText();
			mac=rootNode.get("mac").asText();
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		return mapper.writeValueAsString(resjson);
		}		
    	List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
    	List<GateWayEntity> locklist = gatewayDao.findAll(pageNumber,pageSize,orgname,mac,suborgs);
    	if(locklist != null && locklist.size()> 0){
			ObjectNode tjson = null;
			for(GateWayEntity sys : locklist){
				tjson = mapper.createObjectNode();
				tjson.put("id", sys.getDevcode());
    			tjson.put("descriptor", sys.getDescriptor());
    			tjson.put("mac", sys.getMac());
    			tjson.put("ethip", sys.getEthernet_ip());
    			tjson.put("reguser", sys.getReguser());
    			tjson.put("regdate", sys.getRegdate());
    			tjson.put("orgname", sys.getOrgname());
    			tjson.put("area", sys.getArea());
    			tjson.put("owner", sys.getOwner());
    			tjson.put("orgid", sys.getOrgid());
    			tjson.put("active", sys.getActive());
    			tjson.put("model", sys.getModel());
    			tjson.put("version", sys.getVersion());
    			tjson.put("factory", sys.getFactory());
    			rootnode.add(tjson);
    		}
		}  
    	resjson.put("status", "1");
    	resjson.put("totalCount", gatewayDao.getCount(orgname,mac,suborgs));
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
    	
    	return mapper.writeValueAsString(resjson);  
    }
    
    public void _insertgateway(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	GateWayEntity elock = new GateWayEntity();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String mac = "";   	
    	String area = "";
    	int active = 0;
    	String owner = "";
    	String orgid = "";
    	String descriptor = "";
    	String ckname = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		mac =rootNode.get("mac").asText();
    		area = rootNode.get("area").asText();
    		orgid = rootNode.get("orgid").asText();
    		active = rootNode.get("active").asInt();
    		owner = rootNode.get("owner").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	//权限判断
    	/*resjson = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/网关管理/网关注册");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_insertgeateway");
		ulog.setOrgid(sentity.getOrg_id());

		String uId = UUID.randomUUID().toString().replace("-", "");
		elock.setDevcode(uId);
		elock.setRegdate(dateFormat.format(date));
		elock.setReguser(sentity.getUsername());;
		elock.setArea(area);
		elock.setCname(ckname);
		elock.setOwner(owner);
		elock.setActive(active);
		elock.setDescriptor(descriptor);
		elock.setMac(mac);;
		elock.setOrgid(orgid);
		int flag = gatewayDao.saveGateway(elock);
		if(flag == 0){
			resjson.put("status", "0");
			resjson.put("desc", "注册网关失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}else if(flag == 2) {
			resjson.put("status", "0");
			resjson.put("desc", "重复的网关识别码!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "成功!");
		ulog.setDescriptor("网关[" + mac + "]被添加");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _updategateway(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	String mac = "";    	
    	String area = "";
    	String orgid = "";
    	String owner = "";
    	String descriptor = "";
    	int active = 0;
    	String ckname = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		mac =rootNode.get("mac").asText();
    		area = rootNode.get("area").asText();
    		owner = rootNode.get("owner").asText();
    		active = rootNode.get("active").asInt();
    		orgid =rootNode.get("orgid").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/网关管理/网关编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("_updategateway");

    	try{
    		GateWayEntity gateway = gatewayDao.findByMac(mac);
    		XinLongUtil.xinLongUtil.printlog(log,"更新锁具信息:"+ mac);
    		/*resjson = XinLongUtil.OptAuth(uentity.getId(),jsonstr, sentity);
    		if(!resjson.get("status").asText().equals("1210")){
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}*/
    		ulog.setCreate_check_userid(ckname);
    		gateway.setArea(area);
    		gateway.setCname(ckname);
    		gateway.setDescriptor(descriptor);
    		gateway.setOrgid(orgid);
    		gateway.setOwner(owner);
    		gateway.setActive(active);
    		if(gatewayDao.updateGateway(gateway) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "更新网关信息失败!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
        		return;
    		}
    		
    	}catch(EmptyResultDataAccessException er){
    		resjson.put("status", "0");
			resjson.put("desc", "找不到该网关!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}catch(Exception e){
    		resjson.put("status", "2");
			resjson.put("desc", "未知异常!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	resjson.put("status", "1");
    	resjson.put("desc", "成功!");
    	ulog.setDescriptor("网关[" + mac + "]被编辑");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _gatewayDelete(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String mac="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/网关管理/网关删除");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_gatewayDelete");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			mac=rootNode.get("mac").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		/*resjson = XinLongUtil.OptAuth(id,jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/		
    	
    	if(gatewayDao.delete(mac) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "删除网关失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除网关失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	
		ulog.setDescriptor("网关[" + mac + "]被删除");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _gatewayOff(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String mac="";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/网关管理/网关报废");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_gatewayOff");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			mac=rootNode.get("mac").asText();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		/*resjson = XinLongUtil.OptAuth(id,jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}*/		
	
    	if(gatewayDao.offGateway(mac,dateFormat.format(date),sentity.getUsername()) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "报废网关失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("报废网关失败");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	
		ulog.setDescriptor("网关[" + mac + "]被报废");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void _getGatewayoffLogs(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		ArrayNode rootnode = mapper.createArrayNode();
		String mac="";
		String orgname="";
		int pageNumber = 0;
    	int pageSize = 0;
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/日志管理/网关报废记录");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_getGatewayoffLogs");
		ulog.setOrgid(sentity.getOrg_id());
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			mac=rootNode.get("mac").asText();
			orgname=rootNode.get("orgname").asText();
			pageNumber=rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			ulog.setCreate_check_userid(rootNode.get("ckname").asText());
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
    	List<GateWayEntity> locklist = gatewayDao.findOffAll(pageNumber,pageSize,orgname,mac,suborgs);
    	if(locklist != null && locklist.size()> 0){
			ObjectNode tjson = null;
			for(GateWayEntity sys : locklist){
				tjson = mapper.createObjectNode();
				tjson.put("id", sys.getDevcode());
    			tjson.put("descriptor", sys.getDescriptor());
    			tjson.put("mac", sys.getMac());
    			tjson.put("owner", sys.getReguser());
    			tjson.put("offtime", sys.getOffdate());
    			tjson.put("orgname", sys.getOrgname());
    			tjson.put("area", sys.getArea());
    			tjson.put("offuser", sys.getOffuser());
    			rootnode.add(tjson);
    		}
		}  
    	
		ulog.setDescriptor("");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("系统管理/日志管理/日志导出"));
		}
		resjson.put("totalCount", gatewayDao.getOffCount(orgname,mac,suborgs));
    	resjson.put("pageSize", pageSize);
    	resjson.put("datalist", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    //网关注册上报
    public void GateWayRegister(JsonNode reqjson) throws JsonProcessingException {
    	ObjectMapper mapper = new ObjectMapper(); 
    	String mac =reqjson.get("mac").asText();
		System.out.println("-----Parsed mac:" + mac);
		GateWayEntity gateway = gatewayDao.findByMac(mac);
		//组装响应报文
		RegisterResp resp = new RegisterResp();
		resp.setCode(0);
		resp.setDeviceCode(gateway.getDevcode());
		resp.setMac(mac);
		resp.setTimestamp(reqjson.get("time").asLong());
		MqttHeader mqtth = new MqttHeader();
		mqtth.setDeviceCode("deviceCode");
		mqtth.setMac(mac);
		mqtth.setFrom("CLOUD");
		mqtth.setTo("GATEWAY");
		mqtth.setTime(new Date().getTime());
		mqtth.setType("registerResp");
		mqtth.setData(resp);
		MQTTUtil.publish("t/" + mac, mapper.writeValueAsString(mqtth));
    }
    

    
    public boolean GateWayParseAuth(JsonNode reqjson,String mac) throws JsonProcessingException {
    	ObjectMapper mapper = new ObjectMapper(); 
		MissionEntity mission = null;
		JsonNode jdata = null;
		String fingerprint = ""; 
		String fingerprint2 = "";
		String keysn = "";
		int authmode = 0;
		Date ctime = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddHHmmss");
		ArrayNode marksNode = mapper.createArrayNode();
		ObjectNode resjson = mapper.createObjectNode();
		ObjectNode datajson = mapper.createObjectNode();
		ObjectNode argjson = mapper.createObjectNode();
		ObjectNode valuejson = mapper.createObjectNode();
		resjson.put("from", "CLOUD");
		resjson.put("to", "BLE");
		resjson.put("type", "cmd");
		resjson.put("deviceCode", "xxx");
		resjson.put("mac", mac);
		resjson.put("time", System.currentTimeMillis());
		datajson.put("id", "xxx");
		datajson.put("command", "setAttribute");
		argjson.put("attribute", "resauth");
		try {
			jdata = reqjson.findPath("value");
			fingerprint =jdata.get("fingerprint").asText(); 
			//fingerprint2 =jdata.get("fingerprint2").asText();
			keysn =jdata.get("keysn").asText();
			authmode =jdata.get("authmode").asInt();
		}catch(Exception e) {
			valuejson.put("code", 102);
			valuejson.put("start", dateFormat.format(ctime));
			valuejson.put("end", dateFormat.format(ctime));
			//valuejson.put("authmode", authmode);
			valuejson.put("username", "");
			valuejson.put("username2", "");
			valuejson.put("openmode", 0);
			valuejson.put("locks", marksNode);
			argjson.put("value", valuejson);
			argjson.put("keysn", keysn);
			datajson.put("arguments", argjson);
			resjson.put("data", datajson);
			MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson).replaceAll(" ", ""));
			return false;
		}
		//判断钥匙是否已登记
		/*if(lockDao.findKeyBySn(keysn) == null) {
			//不是登记的钥匙，认证做失败处理
			valuejson.put("code", 104);
			valuejson.put("openmode", 0);
    		valuejson.put("start", dateFormat.format(ctime));
			valuejson.put("end", dateFormat.format(ctime));
    		valuejson.put("username", "");	
    		valuejson.put("username2", "");
    		valuejson.put("locks", marksNode);
    		argjson.put("value", valuejson);
    		argjson.put("keysn", keysn);
    		datajson.put("arguments", argjson);
			resjson.put("data", datajson);
			MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson));
			return false;
		}*/
		//指纹认证
		//test
		//fingerprint = "e8:df:fa:e7:04:88:7a:da:1a:02:00:90:8e:fd:a9:82:b0:bf:25:cb:67:4c:dc:27:03:23:fc:53:37:4e:fe:ef:c2:f7:ab:d0:97:3a:ad:af:3a:e7:2c:e7:b8:46:84:5a:af:86:03:ec:cc:96:c7:b9:98:0c:93:17:1e:24:02:84:9b:bd:e2:c7:dd:b5:a5:e2:22:2c:fa:d9:75:46:98:1d:db:dc:9e:b5:36:a8:ae:23:7b:9e:41:19:96:e7:91:4b:50:a0:c7:e1:ee:5b:c8:16:55:1d:31:7f:1a:dd:34:8e:f7:ca:e2:12:79:45:24:eb:4b:30:3c:eb:24:92:11:9e:20:6d:12:f7:90:de:68:6f:8f:f5:a8:fe:11:76:05:19:96:7a:bf:6c:25:82:f2:0c:8f:2d:a4:8a:29:35:77:c6:a8:e9:18:2e:93:11:a7:74:31:54:7f:d4:fb:c6:58:af:03:b2:be:3c:69:1d:36:b1:d4:8f:51:e4:79:61:02:82:4e:f4:5f:42:97:5a:85:b7:6d:c4:ce:c7:ee:3f:01:0b:eb:c3:db:dd:3d:e9:cb:18:3a:73:cb:17:b6:2b:87:bc:ef:bf:e9:a0:fd:6e:66:4f:05:e3:4e:c5:ef:29:a0:8b:f1:56:43:04:a7:a1:91:e6:8c:9d:a9:97:59:e2:39:85:ad:24:b1:87:5f:e2:7e:67:77:ab:52:7d:17:60:c8:d2:27:ac:d7:b2:53:66:5b:c6:e7:b7:35:7e:7d:eb:54:dd:37:fd:8b:b2:73:4b:79:f3:d0:53:92:f8:9e:fd:22:27:c7:dd:2a:18:5a:62:ab:d8:41:a6:d6:67:ba:e4:09:ae:b4:95:5d:77:8c:d2:05:6c:78:b8:a9:92:07:43:3a:cc:a9:58:e2:d8:78:5d:53:72:96:a9:d2:1d:f4:5c:1c:fb:a6:7b:31:7b:fb:af:46:f6:c1:d3:0e:8a:a5:0a:ae:ad:2d:41:60:06:76:81:a6:a8:6a:70:bf:82:76:a1:1c:a9:4f:70:89:c4:c2:85:47:85:c5:79:3f:4b:99:d1:22:db:dc:6c:69:0e:66:3a:9e:45:d8:77:95:6a:de:c4:0b:c2:29:a8:73:5e:10:cd:01:22:bb:71:3a:9f:c8:f1:23:35:da:ea:6c:f5:07:82:f0:2a:33:45:ae:f9:39:62:d9:03:9e:cb:e8:23:37:c6:e6:7e:76:02:fa:60:ed:e2:bd:b6:1a:ae:7b:7d:ef:eb:31:e7:c5:ae:32:dd:a1:0a:af:e4:d9:d4:6d:0b:d8:bb:4e:44:66:f8:46:c1:09:b1:a4:38:2f:10:38:cb:d9:83:a9:74:6c:56:28:18:44:5f:4e:15:7e:60:b4";
		//fingerprint = fingerprint.replaceAll(":", "").toUpperCase();
		fingerprint = fingerprint.replaceAll("DBDC", "C0");
		fingerprint = fingerprint.replaceAll("DBDD", "DB");
		byte[] fp = ZZFingerUtil.zzFingerUtil.hexStr2Byte(fingerprint);
		String matched = ZZFingerUtil.zzFingerUtil.find(fp);
    	if(matched.equals("")) {
    		valuejson.put("code", 111);
    		valuejson.put("openmode", 0);
    		valuejson.put("start", dateFormat.format(ctime));
			valuejson.put("end", dateFormat.format(ctime));
    		valuejson.put("username", "");	
    		valuejson.put("username2", "");
    		valuejson.put("locks", marksNode);
    		argjson.put("value", valuejson);
    		argjson.put("keysn", keysn);
    		datajson.put("arguments", argjson);
			resjson.put("data", datajson);
			MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson).replaceAll(" ", ""));
    		return false;
    	}    	
    	
    	String[] matches = matched.split("-");
		String username = matches[0];
		//判断用户角色
		int roleflag = userDao.findRoleByUsername(username);
		if(roleflag == 5 || roleflag == 6) {
			//金库人员
			mission = missionDao.findActiveJinkuMissionByAuther(username);
			//获取钥匙授权时间
			if(mission != null) {
				valuejson.put("start", dateFormat.format(ctime));
				valuejson.put("end", dateFormat.format(ctime.getTime() + mission.getKeyvalid() * 1000) );
				valuejson.put("code", 1);
			}else {
				valuejson.put("start", dateFormat.format(ctime));
				valuejson.put("end", dateFormat.format(ctime));
				valuejson.put("code", 103);
			}
			valuejson.put("openmode", 1);
		}else {
			//查找该用户下是否有授权状态的锁具，包括应急人员
			List<LockUserEntity> lockuserlist = lockDao.findAuthedUserLocksByUser(username);
			//组装响应报文
			valuejson.put("openmode", 0);
			if(lockuserlist != null && lockuserlist.size() > 0) {
				
				ObjectNode tjson = null;
				for(LockUserEntity lockuser:lockuserlist) {
					tjson = mapper.createObjectNode();
					tjson.put("locksn", lockuser.getLockid());//这里的locksn是锁具内部Id号
					marksNode.add(tjson);
				}
				mission = missionDao.findMissionById(((LockUserEntity)lockuserlist.get(0)).getMissionid());
				//获取钥匙授权时间
				if(mission != null) {
					
					valuejson.put("start", dateFormat.format(ctime));
					valuejson.put("end", dateFormat.format(ctime.getTime() + mission.getKeyvalid() * 1000) );
					valuejson.put("code", 1);
				}else {
					valuejson.put("start", dateFormat.format(ctime));
					valuejson.put("end", dateFormat.format(ctime));
					valuejson.put("code", 103);
				}
			}else {
				valuejson.put("start", dateFormat.format(ctime));
				valuejson.put("end", dateFormat.format(ctime));
				valuejson.put("code", 103);
			}
			
		}		
		valuejson.put("username", username);	
		valuejson.put("username2", "");
		valuejson.put("locks", marksNode);
		argjson.put("value", valuejson);
		argjson.put("keysn", keysn);
		datajson.put("arguments", argjson);
		resjson.put("data", datajson);
		MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson).replaceAll(" ", ""));
		return true;
    }
    
    //钥匙心跳包解析
    public boolean GateWayBattery(JsonNode reqjson) throws JsonProcessingException {
    	//ObjectMapper mapper = new ObjectMapper(); 		
		String keysn = "";
		//JsonNode jdata = null;
		int electricity = 0;
		try {
			//jdata = reqjson.findPath("data");
			keysn = reqjson.get("keysn").asText(); 
			electricity = reqjson.get("electricity").asInt();
		}catch(Exception e) {
			
			return false;
		}
		if(lockDao.updateKeyElectricity(keysn, electricity) == -1) {
			XinLongUtil.xinLongUtil.printlog(log,"更新钥匙心跳包信息:钥匙电量更新失败");
		}
		
		return true;
    }
    
    public boolean HandleOpenReport(JsonNode reqjson) throws JsonProcessingException {
    	ObjectMapper mapper = new ObjectMapper(); 
		JsonNode jdata = null;
		String username = ""; 
		String username2 = "";
		String keysn = "";
		String locksn = "";
		long opentime = 0;
		String proceed = "";
		int mode = 0;
		String openflag = "";//开锁记录唯一标识码
		ObjectNode resjson = mapper.createObjectNode();
		ObjectNode datajson = mapper.createObjectNode();
		try {
			jdata = reqjson.findPath("data");
			openflag =jdata.get("openflag").asText();
			keysn =jdata.get("keysn").asText();
			username =jdata.get("username").asText(); 
			username2 =jdata.get("username2").asText();			
			locksn =jdata.get("locksn").asText();
			opentime =jdata.get("opentime").asLong();			
			proceed =jdata.get("proceed").asText();
			mode =jdata.get("mode").asInt();
		}catch(Exception e) {
			datajson.put("code", 101);
			datajson.put("openflag", openflag);
			datajson.put("keysn", keysn);
			resjson.put("from", "CLOUD");
			resjson.put("to", "GATEWAY");
			resjson.put("type", "openreport");
			resjson.put("data", datajson);
			MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson));
			return false;
		}
		//记录开锁日志
		LockOpenLogEntity openlog = new LockOpenLogEntity();
		openlog.setId(UUID.randomUUID().toString().replace("-", ""));
		openlog.setOpenflag(openflag);
		openlog.setKeysn(keysn);
		openlog.setLocksn(locksn);
		openlog.setOpentime(new Date(opentime));
		openlog.setOperator(username);
		openlog.setOperator2(username2);
		openlog.setMode(mode);
		openlog.setProceed(proceed);
		if(lockDao.insertopenLog(openlog) == -1) {
			datajson.put("code", 104);
			datajson.put("openflag", openflag);
			datajson.put("keysn", keysn);
			resjson.put("from", "CLOUD");
			resjson.put("to", "GATEWAY");
			resjson.put("type", "openreport");			
			resjson.put("data", datajson);
			MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson));
			return false;
		}
		datajson.put("openflag", openflag);
		datajson.put("keysn", keysn);		
		datajson.put("code", 0);
		resjson.put("from", "CLOUD");
		resjson.put("to", "GATEWAY");
		resjson.put("type", "openreport");
		resjson.put("data", datajson);
		MQTTUtil.publish(MQTT_RES_TOPIC, mapper.writeValueAsString(resjson));
		return true;
    }
}
